package com.huaxin.hxmodulewebsocket.controller;

import com.huaxin.hxmodulewebsocket.handler.MyWebSocketHandler;
import com.huaxin.hxmodulewebsocket.models.SendMessageRequest;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


@Tag(name = "websocket服务")
@RestController
@RequiredArgsConstructor
@RequestMapping("/v1/websocket/pushMessage")
public class WebSocketController {
    private final MyWebSocketHandler webSocketHandler;

    /**
     * 广播消息给所有连接的客户端
     */
    @PostMapping("/broadcast")
    @Operation(summary = "广播消息给所有连接的客户端", description = "广播消息给所有连接的客户端")
    public ResponseEntity<String> broadcastMessage(@RequestBody SendMessageRequest payload) {
        String message = payload.getContent();
        if (message == null || message.trim().isEmpty()) {
            return ResponseEntity.badRequest().body("消息内容不能为空");
        }

        webSocketHandler.broadcastMessage(message);
        return ResponseEntity.ok("广播发送成功，消息: " + message);
    }

    /**
     * 发送消息给指定客户端
     * 请求体示例: {"to": "user1", "message": "你好！"}
     */
    @PostMapping("/sendToClient")
    @Operation(summary = "发送消息给指定客户端", description = "发送消息给指定客户端")
    public ResponseEntity<String> sendToClient(@RequestBody SendMessageRequest payload) {
        String to = payload.getTo();
        String message = payload.getContent();

        if (to == null || to.trim().isEmpty()) {
            return ResponseEntity.badRequest().body("目标客户端ID (to) 不能为空");
        }
        if (message == null || message.trim().isEmpty()) {
            return ResponseEntity.badRequest().body("消息内容不能为空");
        }

        webSocketHandler.sendToClient(to, message);
        return ResponseEntity.ok("消息已发送给 " + to);
    }
}